package com.yulinlin.jdbc.mysql;

import com.yulinlin.core.wrapper.IParamsWrapper;
import com.yulinlin.core.wrapper.IStringConditionWrapper;
import com.yulinlin.core.wrapper.IUpdateWrapper;

public class MysqlUpdateWrapper<E,R> implements IUpdateWrapper<E,R> {

    private IStringConditionWrapper<E,IUpdateWrapper<E,R>> whereWrapper;

    private IParamsWrapper params;

    private StringBuffer columns;

    private String tableName;

    private R endWrapper;

    public MysqlUpdateWrapper(R endWrapper) {
        this.endWrapper = endWrapper;
        this.params = new MysqlParamsWrapper();
        this.whereWrapper = new MysqlStringConditionWrapper(this,params);
        this.columns = new StringBuffer();
    }


    @Override
    public  IUpdateWrapper<E,R>  column(String name, Object params) {
        String v =  this.params.push(params);
        if(columns.length() > 0){
            columns.append(" , ");
        }
        this.columns.append(
                name+" = "+v
        );
        return this;
    }

    @Override
    public IStringConditionWrapper<E,IUpdateWrapper<E,R>> where() {
        return whereWrapper;
    }

    @Override
    public IUpdateWrapper table(String tableName) {
        this.tableName = tableName;
        return this;
    }

    @Override
    public String getSql() {
        StringBuffer sb =  new StringBuffer();
        sb.append("update ");
        sb.append(tableName);
        sb.append(" set ");


        sb.append(columns);

        String where =  this.whereWrapper.getSql();
        if(where.length() > 0){
            sb.append(" where ");
            sb.append(where);
        }
        return sb.toString();
    }

    @Override
    public R end() {
        return endWrapper;
    }

    @Override
    public IParamsWrapper getParams() {
        return params;
    }
}

